// 业务架构设计 - 采购平台
// 
// 架构理念：以公司为主体，个人为执行者的混合架构
// 公司间建立业务关系，个人作为公司代表进行具体操作

// ============= 数据模型设计 =============

// 1. 公司模型 - 业务主体
class Company {
    constructor(data) {
        this.id = data.id;
        this.name = data.name;
        this.type = data.type; // 采购公司、贸易公司、供应链等
        this.area = data.area;
        this.description = data.desc;
        this.businessLicense = data.businessLicense;
        this.contactInfo = data.contactInfo;
        this.establishedDate = data.establishedDate;
        this.businessScope = data.businessScope;
        this.status = 'active'; // active, suspended, deleted
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    // 公司业务能力
    getBusinessCapabilities() {
        const capabilities = {
            '采购公司': ['采购需求发布', '供应商管理', '订单管理'],
            '贸易公司': ['商品供应', '价格管理', '库存管理'],
            '供应链': ['物流配送', '仓储服务', '供应链管理'],
            '商贸集团': ['大宗交易', '批发业务', '分销网络'],
            '进出口': ['国际贸易', '报关服务', '跨境物流'],
            '采购中心': ['集中采购', '招标服务', '政府采购'],
            '电子公司': ['电子产品', '技术支持', '售后服务'],
            '机械公司': ['机械设备', '安装维护', '技术培训']
        };
        return capabilities[this.type] || [];
    }

    // 验证公司资质
    validateQualification() {
        return {
            isValid: this.businessLicense && this.contactInfo,
            issues: []
        };
    }
}

// 2. 用户模型 - 公司执行者
class User {
    constructor(data) {
        this.id = data.id;
        this.name = data.name;
        this.email = data.email;
        this.phone = data.phone;
        this.password = data.password;
        this.avatar = data.avatar;
        this.status = 'active'; // active, inactive, banned
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    // 用户的角色和权限基于其所在的公司和职位
    getPermissions(companyRole) {
        const basePermissions = {
            'admin': ['company_manage', 'user_manage', 'business_full'],
            'manager': ['business_manage', 'order_approve', 'team_manage'],
            'operator': ['order_create', 'product_view', 'basic_operation'],
            'viewer': ['read_only', 'basic_view']
        };
        return basePermissions[companyRole] || basePermissions['viewer'];
    }
}

// 3. 公司-用户关系模型
class CompanyUser {
    constructor(data) {
        this.id = data.id;
        this.companyId = data.companyId;
        this.userId = data.userId;
        this.role = data.role; // admin, manager, operator, viewer
        this.position = data.position; // 具体职位
        this.department = data.department;
        this.permissions = data.permissions;
        this.status = 'active';
        this.joinedAt = new Date();
        this.lastActiveAt = new Date();
    }

    // 检查用户是否有特定权限
    hasPermission(permission) {
        return this.permissions.includes(permission);
    }

    // 获取用户在公司中的完整信息
    getUserCompanyInfo() {
        return {
            role: this.role,
            position: this.position,
            department: this.department,
            permissions: this.permissions,
            joinedAt: this.joinedAt
        };
    }
}

// 4. 公司间业务关系模型
class CompanyRelationship {
    constructor(data) {
        this.id = data.id;
        this.fromCompanyId = data.fromCompanyId;
        this.toCompanyId = data.toCompanyId;
        this.type = data.type; // supplier, customer, partner, competitor
        this.status = data.status; // pending, active, suspended, terminated
        this.businessTerms = data.businessTerms;
        this.creditLimit = data.creditLimit;
        this.contractInfo = data.contractInfo;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    // 验证业务关系
    validateRelationship() {
        if (this.fromCompanyId === this.toCompanyId) {
            return { isValid: false, error: '不能与自己建立业务关系' };
        }
        return { isValid: true };
    }

    // 获取关系描述
    getRelationshipDescription() {
        const descriptions = {
            'supplier': '供应商关系',
            'customer': '客户关系',
            'partner': '合作伙伴关系',
            'competitor': '竞争对手关系'
        };
        return descriptions[this.type] || '未知关系';
    }
}

// 5. 业务交易模型
class BusinessTransaction {
    constructor(data) {
        this.id = data.id;
        this.fromCompanyId = data.fromCompanyId;
        this.toCompanyId = data.toCompanyId;
        this.type = data.type; // purchase, sale, service
        this.items = data.items;
        this.totalAmount = data.totalAmount;
        this.currency = data.currency || 'CNY';
        this.status = data.status; // draft, pending, confirmed, in_progress, completed, cancelled
        this createdBy = data.createdBy; // 用户ID
        this.approvedBy = data.approvedBy; // 用户ID
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    // 计算交易总额
    calculateTotal() {
        return this.items.reduce((total, item) => {
            return total + (item.quantity * item.unitPrice);
        }, 0);
    }

    // 验证交易
    validateTransaction() {
        const issues = [];
        
        if (!this.items || this.items.length === 0) {
            issues.push('交易项目不能为空');
        }

        if (this.fromCompanyId === this.toCompanyId) {
            issues.push('交易双方不能为同一公司');
        }

        return {
            isValid: issues.length === 0,
            issues
        };
    }
}

// ============= 业务逻辑层 =============

// 1. 公司管理服务
class CompanyService {
    constructor() {
        this.companies = new Map(); // 公司数据存储
        this.relationships = new Map(); // 公司关系存储
    }

    // 创建公司
    async createCompany(companyData) {
        const company = new Company(companyData);
        const validation = company.validateQualification();
        
        if (!validation.isValid) {
            throw new Error(`公司资质验证失败: ${validation.issues.join(', ')}`);
        }

        this.companies.set(company.id, company);
        return company;
    }

    // 获取公司信息
    async getCompany(companyId) {
        const company = this.companies.get(companyId);
        if (!company) {
            throw new Error('公司不存在');
        }
        return company;
    }

    // 更新公司信息
    async updateCompany(companyId, updateData) {
        const company = await this.getCompany(companyId);
        Object.assign(company, updateData, { updatedAt: new Date() });
        return company;
    }

    // 建立公司间业务关系
    async establishRelationship(fromCompanyId, toCompanyId, relationshipData) {
        const relationship = new CompanyRelationship({
            ...relationshipData,
            fromCompanyId,
            toCompanyId
        });

        const validation = relationship.validateRelationship();
        if (!validation.isValid) {
            throw new Error(validation.error);
        }

        this.relationships.set(relationship.id, relationship);
        return relationship;
    }

    // 获取公司的业务伙伴
    async getCompanyPartners(companyId, relationshipType) {
        const partners = [];
        
        for (const relationship of this.relationships.values()) {
            if (relationship.fromCompanyId === companyId && 
                (!relationshipType || relationship.type === relationshipType)) {
                partners.push({
                    companyId: relationship.toCompanyId,
                    relationshipType: relationship.type,
                    status: relationship.status
                });
            }
        }

        return partners;
    }
}

// 2. 用户管理服务
class UserService {
    constructor() {
        this.users = new Map(); // 用户数据存储
        this.companyUsers = new Map(); // 公司-用户关系存储
    }

    // 创建用户
    async createUser(userData) {
        const user = new User(userData);
        this.users.set(user.id, user);
        return user;
    }

    // 用户加入公司
    async joinCompany(userId, companyId, roleData) {
        const companyUser = new CompanyUser({
            ...roleData,
            userId,
            companyId
        });

        this.companyUsers.set(companyUser.id, companyUser);
        return companyUser;
    }

    // 获取用户在特定公司的信息
    async getUserCompanyInfo(userId, companyId) {
        for (const companyUser of this.companyUsers.values()) {
            if (companyUser.userId === userId && companyUser.companyId === companyId) {
                return companyUser.getUserCompanyInfo();
            }
        }
        return null;
    }

    // 获取用户的所有公司关系
    async getUserCompanies(userId) {
        const companies = [];
        
        for (const companyUser of this.companyUsers.values()) {
            if (companyUser.userId === userId) {
                companies.push({
                    companyId: companyUser.companyId,
                    role: companyUser.role,
                    position: companyUser.position,
                    department: companyUser.department
                });
            }
        }

        return companies;
    }
}

// 3. 业务交易服务
class BusinessTransactionService {
    constructor() {
        this.transactions = new Map();
    }

    // 创建业务交易
    async createTransaction(transactionData) {
        const transaction = new BusinessTransaction(transactionData);
        
        const validation = transaction.validateTransaction();
        if (!validation.isValid) {
            throw new Error(`交易验证失败: ${validation.issues.join(', ')}`);
        }

        transaction.totalAmount = transaction.calculateTotal();
        this.transactions.set(transaction.id, transaction);
        return transaction;
    }

    // 获取交易历史
    async getTransactionHistory(companyId, options = {}) {
        const { type, status, limit = 50 } = options;
        const transactions = [];

        for (const transaction of this.transactions.values()) {
            if (transaction.fromCompanyId === companyId || 
                transaction.toCompanyId === companyId) {
                
                if (type && transaction.type !== type) continue;
                if (status && transaction.status !== status) continue;
                
                transactions.push(transaction);
            }
        }

        return transactions.slice(0, limit);
    }
}

// ============= API 接口层 =============

// 1. 公司相关API
class CompanyAPI {
    constructor(companyService) {
        this.companyService = companyService;
    }

    // 创建公司
    async createCompany(req, res) {
        try {
            const company = await this.companyService.createCompany(req.body);
            res.json({
                success: true,
                data: company,
                message: '公司创建成功'
            });
        } catch (error) {
            res.status(400).json({
                success: false,
                error: error.message
            });
        }
    }

    // 获取公司信息
    async getCompany(req, res) {
        try {
            const company = await this.companyService.getCompany(req.params.id);
            res.json({
                success: true,
                data: company
            });
        } catch (error) {
            res.status(404).json({
                success: false,
                error: error.message
            });
        }
    }

    // 建立业务关系
    async establishRelationship(req, res) {
        try {
            const relationship = await this.companyService.establishRelationship(
                req.body.fromCompanyId,
                req.body.toCompanyId,
                req.body.relationshipData
            );
            
            res.json({
                success: true,
                data: relationship,
                message: '业务关系建立成功'
            });
        } catch (error) {
            res.status(400).json({
                success: false,
                error: error.message
            });
        }
    }
}

// 2. 用户相关API
class UserAPI {
    constructor(userService) {
        this.userService = userService;
    }

    // 用户注册
    async register(req, res) {
        try {
            const user = await this.userService.createUser(req.body);
            res.json({
                success: true,
                data: user,
                message: '用户注册成功'
            });
        } catch (error) {
            res.status(400).json({
                success: false,
                error: error.message
            });
        }
    }

    // 用户加入公司
    async joinCompany(req, res) {
        try {
            const companyUser = await this.userService.joinCompany(
                req.body.userId,
                req.body.companyId,
                req.body.roleData
            );
            
            res.json({
                success: true,
                data: companyUser,
                message: '加入公司成功'
            });
        } catch (error) {
            res.status(400).json({
                success: false,
                error: error.message
            });
        }
    }
}

// ============= 使用示例 =============

// 初始化服务
const companyService = new CompanyService();
const userService = new UserService();
const transactionService = new BusinessTransactionService();

// 创建示例公司
async function createSampleData() {
    // 创建公司
    const company1 = await companyService.createCompany({
        id: 'company1',
        name: 'ABC采购公司',
        type: '采购公司',
        area: '北京市',
        desc: '专业电子产品采购',
        businessLicense: '123456789',
        contactInfo: { phone: '010-12345678', email: 'info@abc.com' }
    });

    const company2 = await companyService.createCompany({
        id: 'company2',
        name: 'XYZ贸易公司',
        type: '贸易公司',
        area: '上海市',
        desc: '工业原材料供应商',
        businessLicense: '987654321',
        contactInfo: { phone: '021-87654321', email: 'info@xyz.com' }
    });

    // 创建用户
    const user1 = await userService.createUser({
        id: 'user1',
        name: '张三',
        email: 'zhangsan@abc.com',
        phone: '13800138000'
    });

    const user2 = await userService.createUser({
        id: 'user2',
        name: '李四',
        email: 'lisi@xyz.com',
        phone: '13900139000'
    });

    // 用户加入公司
    await userService.joinCompany(user1.id, company1.id, {
        role: 'manager',
        position: '采购经理',
        department: '采购部'
    });

    await userService.joinCompany(user2.id, company2.id, {
        role: 'admin',
        position: '总经理',
        department: '管理层'
    });

    // 建立业务关系
    await companyService.establishRelationship(company1.id, company2.id, {
        type: 'supplier',
        status: 'active',
        businessTerms: '30天账期',
        creditLimit: 1000000
    });

    console.log('示例数据创建完成');
    return { company1, company2, user1, user2 };
}

// 导出模块
export {
    Company,
    User,
    CompanyUser,
    CompanyRelationship,
    BusinessTransaction,
    CompanyService,
    UserService,
    BusinessTransactionService,
    CompanyAPI,
    UserAPI,
    createSampleData
};